<?php

class CategoriesController extends Controller
{
	public $layout='//layouts/column2';

	public function filters()
	{
		return array(
			'accessControl',
			'postOnly + delete',
		);
	}

	public function accessRules()
	{
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('*'),
                'users'=>array('*'),
            ),
        );
	}

	public function actionIndex()
	{
        $id=isset($_GET['id']) ? $_GET['id'] : 1;
        $category=$this->loadModel($id);
        $categories=$category->children;
        $images=array();

        foreach($category->images as $img){
            $image=new Images;
            $images[]=$image->resize($img, 800, 601);
            unset($image, $img);
        }

		$this->render('index',array(
			'categories'=>$categories,
            'category'=>$category,
            'images'=>$images,
		));
	}

    public function actionCreate()
    {
        $model=new Categories;

        if(isset($_POST['Categories']))
        {
            $model->attributes=$_POST['Categories'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        if(isset($_POST['Categories']))
        {
            $model->attributes=$_POST['Categories'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();

        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

	public function loadModel($id)
	{
		$model=Categories::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='categories-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
